package com.jt.www.admin.order_pc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jt.www.admin.order_pc.service.InsPreRecordService;
import com.jt.www.biz.order_pc.service.InsService;
import com.jt.www.dao.mapper.insprerecord.InsPreRecordEntityMapper;
import com.jt.www.model.insprerecord.InsPreRecordEntity;
import com.jt.www.model.insprerecord.vo.InsPreParamVO;
import com.jt.www.model.insprerecord.vo.InsPreRecordExportVO;
import com.jt.www.remote.ProductClient;
import com.jt.www.util.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author admin_ltf
 * @create 2019-05-10 13:30
 */
@Service
public class InsPreRecordServiceImpl implements InsPreRecordService {

    private final static String PRODUCT_NAME = "productName";
    private final static String SOURCE = "source";
    private final static String CHANNEL_NO = "edu";
    @Autowired
    private InsPreRecordEntityMapper insPreRecordEntityMapper;
    @Autowired
    private InsService insService;
    @Autowired
    private ProductClient productClient;

    @Override
    @Transactional
    public Integer addPreRecordInfo(List<InsPreRecordEntity> insPreRecordEntities) {
        int num = 0;
        for (InsPreRecordEntity insPreRecordEntity : insPreRecordEntities) {
            if (insPreRecordEntity == null) {
                return -1;
            }

            //String currentTime = DateUtils.getCurrentTime();
            //insPreRecordEntity.setCreateTime(currentTime);

            JSONObject insContent = insPreRecordEntity.getInsContent();
            insPreRecordEntity.setContent(insContent.toJSONString());
            insPreRecordEntity.setSource(insPreRecordEntity.getSource() != null ? insPreRecordEntity.getSource() : "00");
            if (StringUtils.isEmpty(insPreRecordEntity.getStartDate())) {
                insPreRecordEntity.setStartDate(null);
            }
            if (StringUtils.isEmpty(insPreRecordEntity.getEndDate())) {
                insPreRecordEntity.setEndDate(null);
            }
            num += insPreRecordEntityMapper.insert(insPreRecordEntity);
        }
        return num;
    }

    @Override
    public Integer updatePreRecordInfo(InsPreRecordEntity insPreRecordEntity) {
        if (insPreRecordEntity == null) {
            return -1;
        }
        int num = insPreRecordEntityMapper.updateByPrimaryKeySelective(insPreRecordEntity);

        return num;
    }


    @Override
    public Integer updatePreRecordStatus(String id, String status) {
        InsPreRecordEntity insPreRecordEntity = new InsPreRecordEntity();
        insPreRecordEntity.setId(Long.valueOf(id));
        insPreRecordEntity.setStatus(Integer.valueOf(status));
        int num = insPreRecordEntityMapper.updateByPrimaryKeySelective(insPreRecordEntity);
        return num;
    }

    @Override
    public HashMap<String, Object> searchPreRecordInfo(InsPreParamVO insPreParamVO) {
        if (insPreParamVO.getPage() != null && insPreParamVO.getRows() != null) {
            PageHelper.startPage(insPreParamVO.getPage(), insPreParamVO.getRows());
        }
        List<InsPreRecordEntity> resultList = null;

        // 组装查询条件
        Weekend<InsPreRecordEntity> weekend = Weekend.of(InsPreRecordEntity.class);
        WeekendCriteria<InsPreRecordEntity, Object> criteria = weekend.weekendCriteria();
        if (!StringUtils.isEmpty(insPreParamVO.getProductCode())) {
            criteria.andEqualTo(InsPreRecordEntity::getProductCode, insPreParamVO.getProductCode());
        }
        if (!StringUtils.isEmpty(insPreParamVO.getUserName())) {
            criteria.andEqualTo(InsPreRecordEntity::getUserName, insPreParamVO.getUserName());
        }
        if (!StringUtils.isEmpty(insPreParamVO.getInsuredName())) {
            criteria.andEqualTo(InsPreRecordEntity::getInsuredName, insPreParamVO.getInsuredName());
        }

        if (!StringUtils.isEmpty(insPreParamVO.getProCode())) {
            criteria.andEqualTo(InsPreRecordEntity::getProCode, insPreParamVO.getProCode());
        }

        if (!StringUtils.isEmpty(insPreParamVO.getCityCode())) {
            criteria.andEqualTo(InsPreRecordEntity::getCityCode, insPreParamVO.getCityCode());
        }

        if (!StringUtils.isEmpty(insPreParamVO.getCountryCode())) {
            criteria.andEqualTo(InsPreRecordEntity::getCountryCode, insPreParamVO.getCountryCode());
        }


        if (!StringUtils.isEmpty(insPreParamVO.getStartDate())) {
            criteria.andGreaterThan(InsPreRecordEntity::getStartDate, insPreParamVO.getStartDate());
        }

        if (!StringUtils.isEmpty(insPreParamVO.getEndDate())) {
            criteria.andLessThan(InsPreRecordEntity::getStartDate, insPreParamVO.getEndDate());
        }

        if (!StringUtils.isEmpty(insPreParamVO.getTbStartDate())) {
            criteria.andGreaterThan(InsPreRecordEntity::getTbTime, insPreParamVO.getTbStartDate());
        }

        if (!StringUtils.isEmpty(insPreParamVO.getTbEndDate())) {
            criteria.andLessThan(InsPreRecordEntity::getTbTime, insPreParamVO.getTbEndDate());
        }

        if (!StringUtils.isEmpty(insPreParamVO.getSource())) {
            criteria.andEqualTo(InsPreRecordEntity::getSource, insPreParamVO.getSource());
        }

        criteria.andNotEqualTo(InsPreRecordEntity::getStatus, 3);
        weekend.setOrderByClause("create_time DESC");

        resultList = insPreRecordEntityMapper.selectByExample(weekend);
        if (!CommonUtils.isEmpty(resultList)) {
            resultList.forEach(e -> {
                String content = e.getContent();
                e.setInsContent(JSONObject.parseObject(content));
                formatDateTime(e);
            });
        }
        PageInfo pageinfo = new PageInfo(resultList);
        HashMap<String, Object> map = new HashMap<>();
        map.put("pageCount", pageinfo.getTotal());
        map.put("result", resultList);

        return map;
    }

    @Override
    public HashMap<String, Object> searchInfoByCode(String userCode, String productName, String isNeedContent, Integer page, Integer rows) {
        PageHelper.startPage(page, rows);
        List<InsPreRecordEntity> resultList = null;
        if (StringUtils.isEmpty(isNeedContent)) {
            /*Weekend<InsPreRecordEntity> weekend = Weekend.of(InsPreRecordEntity.class);
            WeekendCriteria<InsPreRecordEntity, Object> criteria = weekend.weekendCriteria();
            criteria.andNotEqualTo(InsPreRecordEntity::getStatus,3);
            criteria.andCondition("(create_user_code = '" + userCode + "' OR user_code = '" + userCode + "')");
            criteria.andCondition("(source = '02' or (source in ('00','01') and status = '2'))");
            if(StringUtil.isNotEmpty(productName)){
                criteria.andLike(PRODUCT_NAME, "%"+productName.trim()+"%");
            }
            weekend.setOrderByClause("create_time DESC");*/


            resultList = insPreRecordEntityMapper.getInsPreRecordList(userCode, productName);


            /*  resultList = insPreRecordEntityMapper.selectByExample(weekend);*/
        } else {
            resultList = insPreRecordEntityMapper.selectListNOContent(userCode);
        }
        if (!CommonUtils.isEmpty(resultList)) {
            Map<String, String> productList = null;
            try {
                productList = insService.getProductList();
            } catch (Exception e) {
                e.printStackTrace();
            }
            Map<String, String> finalProductList = productList;
            resultList.forEach(e -> {
                String content = e.getContent();
                e.setInsContent(JSONObject.parseObject(content));
                formatDateTime(e);

                // 拼装产品logo
                if (finalProductList != null) {
                    String logo = finalProductList.get(e.getProductCode()) == null ? "" : finalProductList.get(e.getProductCode());
                    e.setLogo(logo);
                }

/*
                //根据产品编码查询产品图片ID
                try {
                    String reponseStr = productClient.productdetailsvc(e.getProductCode(),CHANNEL_NO);
                    JSONObject object = JSON.parseObject(reponseStr);

                    JSONObject data = object.getJSONObject("data");
                    String logoUrl = data.getString("logoUrl");
                    e.setLogo(logoUrl);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }*/
            });
        }
        PageInfo pageinfo = new PageInfo(resultList);
        HashMap<String, Object> map = new HashMap<>();
        map.put("pageCount", pageinfo.getTotal());
        map.put("result", resultList);
        return map;
    }

    @Override
    public InsPreRecordEntity searchSingleInfo(String id) {
        InsPreRecordEntity insPreRecordEntity = new InsPreRecordEntity();
        insPreRecordEntity.setId(Long.valueOf(id));
        insPreRecordEntity = insPreRecordEntityMapper.selectByPrimaryKey(insPreRecordEntity);
        insPreRecordEntity.setInsContent(JSONObject.parseObject(insPreRecordEntity.getContent()));
        formatDateTime(insPreRecordEntity);
        return insPreRecordEntity;
    }

    @Override
    public List<InsPreRecordExportVO> exportList(InsPreParamVO insPreParamVO) {
        return insPreRecordEntityMapper.exportList(insPreParamVO);
    }

    private void formatDateTime(InsPreRecordEntity entity) {
        String startDate = entity.getStartDate();
        if (startDate != null) {
            entity.setStartDate(startDate.split("\\.")[0]);
        }
        String endDate = entity.getEndDate();
        if (endDate != null) {
            entity.setEndDate(endDate.split("\\.")[0]);
        }
        String tbTime = entity.getTbTime();
        if (tbTime != null) {
            entity.setTbTime(tbTime.split("\\.")[0]);
        }
        String createTime = entity.getCreateTime();
        if (createTime != null) {
            entity.setCreateTime(createTime.split("\\.")[0]);
        }
    }
}
